import {HubConnectionBuilder} from '@microsoft/signalr/dist/esm/HubConnectionBuilder';
import {HubConnection} from "@microsoft/signalr";
import getCookie from "../functions/getCookie";
import {$host} from "./index";

const hubUrl = 'https://localhost:7050/ws/chathub';

let connection: HubConnection | null = null;

export const startSignalRConnection = (onReceiveMessage: (message: any) => void, onConnectionUpdate: (usersOnline: string[]) => void): Promise<void> => {
    return new Promise((resolve, reject) => {
        connection = new HubConnectionBuilder()
            .withUrl(hubUrl, {accessTokenFactory: () => getCookie('.AspNetCore.Identity.Application')!})
            .withAutomaticReconnect()
            .build();

        connection.on('ReceiveMessage', onReceiveMessage);

        connection.on('OnConnection', (data) => {
            console.log('OnConnection received', data);
            onConnectionUpdate(data._usersOnline);
        });

        connection.on('OnDisconnection', (data) => {
            console.log('OnDisconnection received', data);
            onConnectionUpdate(data._usersOnline);
        });

        connection.start()
            .then(() => {
                console.log('SignalR Connected');
                resolve(); // Разрешить промис после успешного подключения
            })
            .catch((error: Error) => {
                console.error('SignalR Connection Error: ', error);
                reject(error); // Отклонить промис в случае ошибки
            });
    });
};

export const stopSignalRConnection = (): void => {
    if (connection) {
        connection.stop()
            .then(() => console.log('SignalR Disconnected'))
            .catch((error: Error) => console.error('SignalR Disconnection Error: ', error));
    }
};

export const getOldMessages = async () => {
    try {
        const response = await $host.get('/api/Chat/GetMessages');
        return response.data.messages;
    } catch (error) {
        console.error('Ошибка при получении старых сообщений:', error);
        throw error;
    }
};

export const sendMessage = async (message: string) => {
    if (!connection || connection.state !== "Connected") {
        console.error('Cannot send message. SignalR connection is not established.');
        return;
    }

    try {
        await connection.invoke('SendMessageAsync', message);
        console.log("Message sent");
    } catch (error) {
        console.error("Error sending message: ", error);
    }
};